package com.lease.web.admin.service.impl;

import com.kangaroohy.minio.configuration.MinioProperties;
import com.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 使用minio实现文件上传接口
        // 生成当前日期作为文件夹名，格式为年月日
        String dateFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
        // 生成UUID作为文件名前缀
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFileName = file.getOriginalFilename();
        // 拼接完整的对象路径
        String objectName = dateFolder + "/" + uuid + "_" + originalFileName;

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket("lease")
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType("image/jpeg") // 设置文件格式为图片格式
                .build();
        minioClient.putObject(putObjectArgs);

        // 从minioproperties中拿到端点拼接对象路径，返回url给前端
        return minioProperties.getEndpoint() + "/lease/" + objectName;
    }
}
